from pathlib import Path

from PyQt5.QtCore import QRunnable, QObject, QThread, pyqtSignal

from .obj_to_png import restore_tool, get_file

progressNum = 0


class WorkerSignals(QObject):
    signal = pyqtSignal(str, str, int)


workerSignals = WorkerSignals()


class Runnable(QRunnable):
    signal = None

    def __init__(self, obj_path, png_path, save, total):
        super(Runnable, self).__init__()
        self.obj_path = str(obj_path)
        self.png_path = str(png_path)
        self.save = str(save)
        self.total = total
        self.setAutoDelete(True)

    def run(self) -> None:
        global progressNum
        progressNum += 1
        restore_tool(self.obj_path, self.png_path, self.save)
        workerSignals.signal.emit(
            f'共{self.total}个文件，已合并{progressNum}个文件',
            f'{self.png_path}合并成功',
            int((progressNum / self.total * 100))
        )


class CraftThread(QThread):
    """
    Thread for merging obj and texture2D to png
    """
    signal = pyqtSignal(str, str, int)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.meshPath = ''
        self.texture2DPath = ''
        self.savePath = ''

    def run(self) -> None:
        png_list = get_file(self.texture2DPath)
        obj_list = get_file(self.meshPath)
        total = len(obj_list)
        for index, png_file in enumerate(png_list):
            name = Path(png_file).stem
            obj = Path(self.meshPath) / f'{name}-mesh.obj'
            save = Path(self.savePath) / f'{name}.png'
            restore_tool(obj, png_file, save)
            self.signal.emit(
                f'共{total}个文件，已合并{index}个文件',
                f'{png_file}合并成功',
                int((index / total * 100))
            )
        labelText = f'共{total}个文件，已合并{total}个文件'
        self.signal.emit(labelText, '图片提取合并完成！！！', 100)

    def setValues(self, meshPath: str, texture2DPath: str, savePath: str):
        self.meshPath = meshPath
        self.texture2DPath = texture2DPath
        self.savePath = savePath
        self.start()
